package cn.bxc.job;

import cn.bxc.IOrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 检测未接收到或未正确处理的支付回调通知
 * @author bxc
 * @date 2025/6/9 15:41
 **/
@Slf4j
@Component
public class NoPayOrderNotifyJob {
    @Resource
    private IOrderService orderService;
    @Resource
    private AlipayClient alipayClient;

    @Scheduled(cron = "0 0/3 * * * ?")
    public void exec(){
        try {
            log.info("任务：检测未接收到或未正确处理的支付回调通知");
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if(orderIds == null || orderIds.isEmpty()){
                return;
            }
            for (String orderId : orderIds) {
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel bizModel = new AlipayTradeQueryModel();
                bizModel.setTradeNo(orderId);
                request.setBizModel(bizModel);
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                String code = response.getCode();
                if("10000".equals(code)){
                    orderService.changeOrderPaySuccess(orderId);
                }
            }
        } catch (Exception e) {
            log.error("检测未接收到或未正确处理的支付回调通知失败",e);
        }
    }
}
